import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import {
  ApiOperation,
  ApiProperty,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import { AuthService, JwtResponse } from './auth.service';

class LoginDto {
  @ApiProperty({ description: '用户名', example: 'admin' })
  username: string;

  @ApiProperty({ description: '密码', example: 'password123' })
  password: string;
}

@ApiTags('auth')
@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('login')
  @ApiOperation({
    summary: '用户登录',
    description: '验证用户名和密码并返回JWT令牌和用户信息',
  })
  @ApiResponse({
    status: 200,
    description: '登录成功，返回JWT令牌和用户信息',
    type: JwtResponse,
  })
  @ApiResponse({ status: 400, description: '用户名或密码不正确' })
  async login(@Body() loginDto: LoginDto): Promise<JwtResponse> {
    console.log('loginDto', loginDto);
    const user = await this.authService.validateUser(
      loginDto.username,
      loginDto.password,
    );
    if (!user) {
      throw new BadRequestException('用户名或密码不正确');
    }
    return this.authService.login(user);
  }
}
